package com.elcl.activity.fragment;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

import com.elcl.andbaselibrary.R;

/**
 * @author lichunlin
 * 使用地方：在Viewpaer+fragment的地方使用，可以将fragment暂停，不用重复利用
 * 使用方法：构造创建方法，然后调用showNewPage（）；
 */
public class ViewPagerFragmentShowUtils {
	private FragmentActivity fragmentActivity;//
	private List<Fragment> list_frag;// 需要替换的fragment

	private int current_page = 0;// 当前展示的页数
	private int new_page = 0;// 新的页数（将要加载的page）
	private int layoutId;// 需要替换的布局
	private boolean isShowAnimations = true;// 是否显示切换fragment的动画

	public ViewPagerFragmentShowUtils(int layoutId, List<Fragment> list_frag,
			FragmentActivity fragmentActivity) {
		super();
		this.layoutId = layoutId;
		this.list_frag = list_frag;
		this.fragmentActivity = fragmentActivity;
	}

	public void showNewPage(int new_page) {
		this.new_page = new_page;
		for (int i = 0; i < list_frag.size(); i++) {
			if (i == new_page) {
				Fragment fragment = list_frag.get(new_page);
				FragmentTransaction ft = obtainFragmentTransaction();

				getCurrentFragment().onPause(); // 暂停当前tab

				if (fragment.isAdded()) {
					fragment.onResume(); // 启动目标tab的onResume()
				} else {
					ft.add(layoutId, fragment);
				}
				showTab(); // 显示目标tab
				ft.commit();
				break;
			}
		}
	}

	public Fragment getCurrentFragment() {
		return list_frag.get(current_page);
	}

	/**
	 * 切换tab
	 * 
	 */
	private void showTab() {
		for (int i = 0; i < list_frag.size(); i++) {
			Fragment fragment = list_frag.get(i);
			FragmentTransaction ft = obtainFragmentTransaction();
			if (new_page == i) {
				ft.show(fragment);
			} else {
				ft.hide(fragment);
			}
			ft.commit();
		}
		current_page = new_page; // 更新目标tab为当前tab
	}

	/**
	 * 获取一个带动画的FragmentTransaction
	 */
	private FragmentTransaction obtainFragmentTransaction() {
		FragmentTransaction ft = fragmentActivity.getSupportFragmentManager()
				.beginTransaction();
		if (isShowAnimations) {// 设置切换动画,如果
			if (new_page > current_page) {// 如果显示的page大于原来的
				ft.setCustomAnimations(R.anim.anim_right_in,
						R.anim.anim_left_out);
			} else {
				ft.setCustomAnimations(R.anim.anim_left_in,
						R.anim.anim_right_out);
			}
		}
		return ft;
	}

	/**
	 * 切换fragment是否显示动画
	 * 在调用showNewPage前使用
	 * @param isShowAnimations
	 */
	public void setIsShowAnimations(boolean isShowAnimations) {
		this.isShowAnimations = isShowAnimations;
	}

}
